/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatroom.com.frame;

import chatroom.com.chatEvent.Chat;
import chatroom.com.clientserver.ChatServer;
import java.awt.Color;
import java.awt.FileDialog;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;

/**
 *
 * @author 李鹏飞
 */
public class SendFileJFrame extends javax.swing.JFrame {

    private String myname;
    private String toname;
    private String toIp;
    PrintWriter out;
    public File file;
    JTextPane gongliao;

    /**
     * Creates new form SendFileJFrame
     */
    public SendFileJFrame() {
        initComponents();
    }

    public SendFileJFrame(String myname, String name, String ipAddress, PrintWriter out, JTextPane gongliao) {
        super("发送文件");
        initComponents();
        this.myname = myname;
        this.toname = name;
        this.out = out;
        toIp = ipAddress;
        this.gongliao = gongliao;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        filename = new javax.swing.JTextField();
        sendfile = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel1.setText("给他/她发送文件：");

        sendfile.setText("发送文件");
        sendfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendfileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(filename, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sendfile)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(22, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(filename, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sendfile))
                .addGap(14, 14, 14))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void sendfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendfileActionPerformed
        sendFileToOthers(toname, out);
    }//GEN-LAST:event_sendfileActionPerformed
    public void sendFileToOthers(String toName, PrintWriter out) {
        FileDialog fd = new FileDialog(this, "发送文件给： " + toName + "...", FileDialog.LOAD);
        fd.setVisible(true);
        if (fd.getDirectory() != null && fd.getFile() != null) {
            filename.setText(fd.getDirectory() + fd.getFile());
            out.println("sendfile&" + toName + "&" + this.myname + "&" + fd.getFile().toString() + "&" + this.toIp);
            out.flush();

        }
        System.out.println(fd.getDirectory() + fd.getFile());
        File f = new File(fd.getDirectory(), fd.getFile());
        sendFile(f);
        this.dispose();

    }

    public void sendFile(File file) {
        try {
            int sendFilePort = 4444;
            ServerSocket ss = new ServerSocket(sendFilePort);
            Socket socket = ss.accept();
            OutputStream os = socket.getOutputStream();
            byte[] buf = new byte[512];
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            PrintWriter pw = new PrintWriter(os);
            String line = "send";
            while (true) {
                line = br.readLine();
                if (!line.equals("refuse")) {
                    int leg = 0;
                    FileInputStream fis = new FileInputStream(file);
                    while ((leg = fis.read(buf, 0, buf.length)) != -1) {
                        os.write(buf, 0, leg);
                    }
                    os.flush();
                    os.close();
                    System.out.println("文件传输完成 ");
                    Chat.sysXiaoxi(gongliao, "发送给" + toname + "的文件，发送成功", Color.blue, 13);
                } else if (line.equals("refuse")) {
                    Chat.sysXiaoxi(gongliao, "对方拒绝接收您发送的文件，您可以选择重新发送", Color.blue, 13);
                    pw.println("exit");
                    pw.flush();
                    pw.close();
                    os.close();
                    br.close();
                    socket.close();
                    ss.close();
                    break;
                }
                if (line.equals("endsendfile")) {
                    pw.println("exit");
                    pw.flush();
                    pw.close();
                    os.close();
                    br.close();
                    socket.close();
                    ss.close();
                    break;
                }
            }


        } catch (Exception e) {
        }
    }

    public static void receiveFile(String ip, String fileName, int isReceive,JTextPane jtp) throws Exception {
        Socket sock = new Socket(ip, 4444);
        InputStream is = sock.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        PrintWriter pw = new PrintWriter(sock.getOutputStream());

        String instr;
        byte[] buf = new byte[512];


        while (true) {
            if (isReceive == 1) {//接收
                pw.println("recei");
                pw.flush();
                File f = new File("C:\\Documents and Settings\\Administrator\\My Documents\\NetBeansProjects\\chatroom\\receive\\" + fileName);
                if (!f.exists()) {
                    f.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(f);
                int leg = 0;
                while ((leg = is.read(buf, 0, buf.length)) != -1) {
                    fos.write(buf, 0, leg);
                }
                fos.close();
                Chat.sysXiaoxi(jtp, "文件" + f + "接收成功，文件保存在receive文件夹下面", Color.blue, 13);
                pw.println("endsendfile");
                pw.flush();
            } else if (isReceive == 0) {//拒绝接收，向那个服务器发送拒绝命令
               
                pw.println("refuse");
                pw.flush();
                 Chat.sysXiaoxi(jtp, "您拒绝接收文件" + fileName , Color.blue, 13);
            }
            instr = br.readLine();
            if (instr.equals("exit")) {
                break;
            }

            //System.out.println( "服务器返回的字符串是: "+instr); 
        }

        pw.close();
        br.close();
        is.close();
        sock.close();



    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SendFileJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SendFileJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SendFileJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SendFileJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SendFileJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField filename;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton sendfile;
    // End of variables declaration//GEN-END:variables

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }
}
